package cn.sylinx.horm.example.section2;

import java.io.Serializable;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.example.entity.MyExample2;

@Profile("section2")
@Component
public class Section2 implements CommandLineRunner {

    private SqlClient sqlClient;

    public Section2(SqlClient sqlClient) {
        this.sqlClient = sqlClient;
    }

    @Override
    public void run(String... args) throws Exception {

        updateToNull();
    }

    void updateToNull() {
        // 更新
        // 支持number字段设置为null，当number字段为null，会将标中number字段设置为null
        Long pk = 2L;
        MyExample2 me = new MyExample2().withNullable(MyExample2::getNumber);
        me.setName("my_name_not_null");
        me.setNumber(null);
        me.setId(pk);
        int updateCount = sqlClient.update(me);
        System.out.println("updateToNull updateCount -> " + updateCount);
        
        MyExample2 updated = sqlClient.get(pk, MyExample2.class);
        System.out.println("updateToNull updated MyExample2 -> " + updated);
    }

    void delete() {
        MyExample2 me = new MyExample2();
        me.setId(1L);
        int count = sqlClient.delete(me);
        System.out.println("MyExample2 delete count -> " + count);
    }

    void updateWithOptLock() {
        // 更新（乐观锁）
        MyExample2 me = new MyExample2();
        me.setName("my_name_optlock");
        me.setNumber("my_number_optlock");
        me.setRecordVersion(1L); // 版本号，当更新成功时，版本号会自动加1
        me.setId(1L);
        int updateCount = sqlClient.update(me);
        System.out.println("MyExample2 updateWithOptLock -> " + updateCount);
    }

    void query() {
        // 查询
        Long pk = 1L;
        MyExample2 me = sqlClient.get(pk, MyExample2.class);
        System.out.println("MyExample2 get -> " + me);
    }

    void update() {
        // 更新
        MyExample2 me = new MyExample2();
        me.setName("my_name_u");
        me.setNumber("my_number_u");
        me.setId(1L);
        int updateCount = sqlClient.update(me);
        System.out.println("MyExample2 updateCount -> " + updateCount);
    }

    void create() {
        // 新增
        MyExample2 me = new MyExample2();
        me.setName("my_name");
        me.setNumber("my_number");
        me.setRecordVersion(1L);
        Serializable pk = sqlClient.save(me);
        System.out.println("MyExample2 save pk -> " + pk);
    }
}
